package com.gavin.sample.security;

import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class SHA1withRSAUtil {
	
	public static byte[] signWithOwnImpl(byte[] content, PrivateKey privateKey) throws Exception {
		MessageDigest md = MessageDigest.getInstance(AlgorithmConstants.SHA1);
		byte[] bytes = md.digest(content);
		
		Cipher cipher = Cipher.getInstance(AlgorithmConstants.RSA);
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		byte[] encryptBytes = cipher.doFinal(bytes);
		return encryptBytes;
	}
	
	public static boolean verifyWIthOwnImpl(byte[] content, byte[] sign, PublicKey publicKey) throws Exception {
		MessageDigest md = MessageDigest.getInstance(AlgorithmConstants.SHA1);
		byte[] bytes = md.digest(content);
		
		Cipher cipher = Cipher.getInstance(AlgorithmConstants.RSA);
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
		byte[] decryptBytes = cipher.doFinal(sign);
		
		if (Base64.encodeBase64String(decryptBytes).equals(Base64.encodeBase64String(bytes))) {
			return true;
		} else {
			return false;
		}
	}
	
	public static byte[] sign(byte[] content, PrivateKey privateKey) throws Exception {
		Signature signature = Signature.getInstance(AlgorithmConstants.SHA1withRSA);
		signature.initSign(privateKey);
		signature.update(content);
		return signature.sign();
	}
	
	public static boolean verify(byte[] content, byte[] sign, PublicKey publicKey) throws Exception {
		Signature signature = Signature.getInstance(AlgorithmConstants.SHA1withRSA);
		signature.initVerify(publicKey);
		signature.update(content);
		return signature.verify(sign);
	}
}
